package cn.edu.hqu.example.bj.experiment_7;

import android.annotation.SuppressLint;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


    StringBuilder sb;
    TextView showx;
    TextView showy;
    TextView showz;

    SensorManager systemService;

    Sensor sensor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        showx=(TextView)findViewById(R.id.t_1);
        showy=(TextView)findViewById(R.id.t_2);
        showz=(TextView)findViewById(R.id.t_3);

        //获得传感器服务
        systemService=(SensorManager)getSystemService(SENSOR_SERVICE);
        //获得加速传感器服务
        sensor=systemService.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    }

    //重写
    @Override
    protected void onResume() {

        super.onResume();
        systemService.registerListener(new SensorEventListener(){

            @SuppressLint("SetTextI18n")
            @Override
            public void onSensorChanged(SensorEvent event) {
                sb=new StringBuilder();
                switch(event.sensor.getType()){
                    case Sensor.TYPE_ACCELEROMETER:{
                        float values[]=event.values;
                        showx.setText("x"+String.valueOf(values[0]));
                        showy.setText("y"+String.valueOf(values[1]));
                        showz.setText("z"+String.valueOf(values[2]));

                    }
                }
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {

            }
        },sensor,SensorManager.SENSOR_DELAY_NORMAL);

    }

    @Override
    protected  void onPause(){
        //可以再暂停时将监听器取消
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}
